package blog.gui;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemListener;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;

import blog.SysRuntime;
import blog.controller.ConstAction;

public class MediaFileSelectorImpl extends List implements CommandListener, FileSystemListener
{
	protected Image UPDIR_IMAGE;

	protected Image FOLDER_IMAGE;

	protected Image FILE_IMAGE;

	protected static final String FILE_SEPARATOR = (System.getProperty( "file.separator" ) != null) ? System.getProperty( "file.separator" ) : "/";

	protected static final String FILE_SEPARATOR_ALT = "/";

	private final static String UP_DIR = "..";

	private final Command openCommand = new Command( "Open", Command.ITEM, 1 );

	private final Command cancelCommand = new Command( "Cancel", Command.CANCEL, 1 );

	private Vector rootsList = new Vector( );

	// Stores the current root, if null we are showing all the roots
	private FileConnection currentRoot = null;

	protected byte[] mediaDataBlock = null;

	protected String selectedFile = null;

	protected String selectedURL = null;

	protected boolean bCurFolderIsARoot = true;

	public MediaFileSelectorImpl()
	{

		super( "Media", List.IMPLICIT );

		addCommand( openCommand );
		addCommand( cancelCommand );
		setSelectCommand( openCommand );
		setCommandListener( this );

		try
		{
			FOLDER_IMAGE = Image.createImage( "/folder_icon.png" );
			FILE_IMAGE = Image.createImage( "/file_icon.png" );
			UPDIR_IMAGE = Image.createImage( "/up_dir_icon.png" );
		}
		catch (IOException imgOpenEx)
		{
		}
	} //constructor

	/**
	 * Cleanup any allocated resources immediately.
	 */
	public void doCleanup()
	{
		this.selectedFile = null;
		this.selectedURL = null;

		if (null != currentRoot)
		{
			try
			{
				currentRoot.close( );
			}
			catch (IOException ioEx)
			{
			}
			currentRoot = null;
		}

		mediaDataBlock = null;

	}//doCleanup

	public void commandAction(Command c, Displayable d)
	{
		if (c == openCommand)
		{
			openSelected( );
		}
		else if (c == cancelCommand)
		{
			doCleanup( );
			
			SysRuntime.guiManager.back();
		}

	}//commandAction

	public void resetRoots()
	{
		String defaultPhotosDir = System.getProperty( "fileconn.dir.photos" );
		loadRoots( );

		if (defaultPhotosDir != null)
		{
			try
			{
				currentRoot = (FileConnection) Connector.open( defaultPhotosDir, Connector.READ );
				displayCurrentRoot( );
			}
			catch (Exception e)
			{
				displayAllRoots( );
			}
		}
		else
		{
			displayAllRoots( );
		}
	}//resetRoots

	protected void displayAllRoots()
	{
		setTitle( "Media" );
		deleteAll( );
		Enumeration roots = rootsList.elements( );
		while (roots.hasMoreElements( ))
		{
			String root = (String) roots.nextElement( );
			append( root.substring( 1 ), FOLDER_IMAGE );
		}
		currentRoot = null;
	}//displayAllRoots

	protected void loadRoots()
	{
		bCurFolderIsARoot = true;

		if (!rootsList.isEmpty( ))
		{
			rootsList.removeAllElements( );
		}

		try
		{
			Enumeration roots = FileSystemRegistry.listRoots( );
			while (roots.hasMoreElements( ))
			{
				rootsList.addElement( FILE_SEPARATOR + (String) roots.nextElement( ) );
			}
		}
		catch (Throwable e)
		{
		}
	}//loadRoots

	protected void openSelected()
	{
		int selectedIndex = getSelectedIndex( );

		if (selectedIndex >= 0)
		{
			selectedFile = getString( selectedIndex );

			if (null != selectedFile)
			{
				if (selectedFile.endsWith( FILE_SEPARATOR ) || selectedFile.endsWith( FILE_SEPARATOR_ALT ))
				{
					try
					{
						if (null == currentRoot)
						{
							currentRoot = (FileConnection) Connector.open( "file:///" + selectedFile, Connector.READ );
						}
						else
						{
							currentRoot.setFileConnection( selectedFile );
						}
						displayCurrentRoot( );
					}
					catch (Exception e)
					{
					}
				}
				else if (selectedFile.equals( UP_DIR ))
				{
					String curRootName = currentRoot.getPath( ) + currentRoot.getName( );

					if (rootsList.contains( curRootName ))
					{
						displayAllRoots( );
					}
					else
					{
						try
						{
							currentRoot.setFileConnection( UP_DIR );
							displayCurrentRoot( );
						}
						catch (IOException e)
						{
						}
						catch (IllegalArgumentException e)
						{
							//there's something hosed with this path-- jump back to roots
							displayAllRoots( );
						}
					}
				}
				else
				{

					//the user has selected a particular file

					SysRuntime.actionManager.addAction(null, ConstAction.ACT_FILE_SELECT_FINISH, this);
				}
			}
			else
			{
			}
		}
	}//openSelected

	public void doNotifyOpComplete()
	{

		if (null != currentRoot)
		{
			selectedURL = currentRoot.getURL( ) + selectedFile;

			try
			{
				currentRoot.close( );
			}
			catch (IOException ioEx)
			{
			}
		}

		currentRoot = null; //reset it

		BlogEntryGui.getInstance().photoFinished( this );
	}

	protected void displayCurrentRoot()
	{

		try
		{
			if (null != currentRoot)
			{
				String rootName = currentRoot.getName( );
				if ((rootName == null) || (rootName.length( ) < 1))
					rootName = selectedFile;

				setTitle( "[" + rootName + "]" );

			}
			else setTitle( "Media" );

			// open the root
			deleteAll( );
			append( UP_DIR, UPDIR_IMAGE );

			// list all dirs
			Enumeration listOfDirs = currentRoot.list( "*", false );
			while (listOfDirs.hasMoreElements( ))
			{
				String currentDir = (String) listOfDirs.nextElement( );

				if (currentDir.endsWith( FILE_SEPARATOR ) || currentDir.endsWith( FILE_SEPARATOR_ALT ))
				{
					append( currentDir, FOLDER_IMAGE );
				}
			}
			// list all png files and dont show hidden files
			Enumeration listOfFiles = currentRoot.list( "*.png", false );
			while (listOfFiles.hasMoreElements( ))
			{
				String currentFile = (String) listOfFiles.nextElement( );
				append( currentFile, FILE_IMAGE );
			}

			listOfFiles = currentRoot.list( "*.jpg", false );
			while (listOfFiles.hasMoreElements( ))
			{
				String currentFile = (String) listOfFiles.nextElement( );
				append( currentFile, FILE_IMAGE );
			}

			listOfFiles = currentRoot.list( "*.gif", false );
			while (listOfFiles.hasMoreElements( ))
			{
				String currentFile = (String) listOfFiles.nextElement( );
				append( currentFile, FILE_IMAGE );
			}

		}
		catch (Exception e)
		{
		}

	}//displayCurrentRoot

	public String getMediaName()
	{
		return selectedFile;
	}//getMediaName

	public String getMediaMimeType()
	{
		String szMimeType = null;

		if (null != selectedFile)
		{
			String copyName = selectedFile.toLowerCase();
			if ((copyName.indexOf( "jpg" ) > 0) || (copyName.indexOf( "jpeg" ) > 0))
				szMimeType = "image/jpeg";
			else if (copyName.indexOf( "png" ) > 0)
				szMimeType = "image/png";
			else if (copyName.indexOf( "gif" ) > 0)
				szMimeType = "image/gif";
			else if (copyName.indexOf( "bmp" ) > 0)
				szMimeType = "image/bmp";
		}

		return szMimeType;
	}//getMediaMimeType

	public Image getThumbnail(int width, int height)
	{
		Image thumbImage = null/*FILE_IMAGE*/;
		//String mediaType = getMediaMimeType( );

		//if (null != mediaType)
		//{
			try
			{
				byte[] datablock = getMediaData( );
				thumbImage = Image.createImage( datablock, 0, datablock.length );
			}
			catch (java.lang.OutOfMemoryError oom)
			{
			}
			catch (Exception ex)
			{
			}
		//}

//		if (thumbImage.getWidth( ) > (2 * width))
//		{
//			thumbImage = FILE_IMAGE;
//		}


		return thumbImage;
	}//getThumbnail

	public byte[] getMediaData()
	{
		if (null == mediaDataBlock)
		{
			if (null != selectedURL)
			{
				try
				{

					long availSize = 0;


					currentRoot = (FileConnection) Connector.open( selectedURL );

					availSize = currentRoot.fileSize( );


					if (availSize > 0)
					{
						try
						{
							InputStream is = currentRoot.openInputStream( );

							System.gc( );
							mediaDataBlock = new byte[(int) availSize];

							is.read( mediaDataBlock );
							is.close( );

						}
						catch (IOException ioEx)
						{
						}
						catch (java.lang.OutOfMemoryError oom)
						{
						}
					}

					currentRoot.close( ); //no longer needed
					currentRoot = null;
				}
				catch (IOException ioEx)
				{
				}
				catch (Exception ex)
				{
				}
			}
		}
		else
		{
		}

		return mediaDataBlock;

	}//getMediaData

	public void rootChanged(int changeType, String strArg)
	{
	}

} //class KMediaFileSelector

//class KMediaFileSelectorKicker implements Runnable
//{
//	public KMediaFileSelectorKicker(MediaFileSelectorImpl aTarget)
//	{
//		target = aTarget;
//	}
//
//	public void run()
//	{
//		if (null != target)
//		{
//			target.doNotifyOpComplete( );
//		}
//	}
//
//	MediaFileSelectorImpl target;
//}